package com.xhd.demo.atomic;

import java.util.Random;
import java.util.concurrent.atomic.LongAccumulator;

public class LongAccumulatorDemo {
    /**
     * 自定义操作：两个数相乘
     */
    public static void mult() {
        LongAccumulator longAccumulator = new LongAccumulator((left, right) ->
                left * right, 2L);
        longAccumulator.accumulate(3L);
        System.out.println(longAccumulator.longValue());
    }


    public static void main(String[] args) throws InterruptedException {
//        mult();

        //自定义操作：取最大值
        LongAccumulator longAccumulator = new LongAccumulator(Long::max, Long.MIN_VALUE);
        Thread[] ts = new Thread[1000];
        for (int i = 0; i < 1000; i++) {
            ts[i] = new Thread(() -> {
                Random random = new Random();
                long value = random.nextLong();
                // 比较value和上一次的比较值，然后存储较大者
                longAccumulator.accumulate(value);
            });
            ts[i].start();
        }
        for (int i = 0; i < 1000; i++) {
            ts[i].join();
        }
        System.out.println(longAccumulator.longValue());
    }
}
